# coding = utf-8
import os
import time

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from polls.models import Question, Choice, VoteDetail, ChoiceImage
from wine import settings
from .serializers import QuestionSerializer, ChoiceSerializer, VoteDetailSerializer, ChoiceImageSerializer


class QuestionViewSet(ModelViewSet):
    """投票管理"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class ChoiceViewSet(ModelViewSet):
    """投票管理"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Choice.objects.all()
    serializer_class = ChoiceSerializer

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class VoteDetailViewSet(ModelViewSet):
    """投票详情"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = VoteDetail.objects.all()
    serializer_class = VoteDetailSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class ChoiceImageUploadAPIView(APIView):
    # authentication_classes = ()
    def post(self, request, *args, **kwargs):
        # 接收文件
        content_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff']
        file = request.FILES.get('image', None)
        choice_id = request.data.get("choice_id", None)
        if file and file.content_type in content_types:
            print(file, choice_id)
            upload_path = ChoiceImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'choice_id': choice_id,
                'image': file_url,
            }

            obj = ChoiceImage.objects.create(**data)
            dict_obj = {
                "id":   obj.id,
                "choice_id": obj.choice_id,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class ChoiceImageViewSet(ModelViewSet):
    """选项图片"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = ChoiceImage.objects.all()
    serializer_class = ChoiceImageSerializer


